import express, { Request, Response } from 'express';
import { Book } from '../model';

const router = express.Router();

router.get('/', async (req: Request, res: Response) => {
    const { current = 1, pageSize = 10, name, author, category } = req.query;
    const data = await Book.find({
        ...(name && { name }) as any,
        ...(author && { author }) as any,
        ...(category && { category }) as any
    })
        .skip((Number(current) - 1) * Number(pageSize)) // 跳过第current * pageSize 条数据
        .populate('category')
        .limit(Number(pageSize)); // 取出后面的 pageSize 条数据
    const total = await Book.countDocuments({
        ...(name && { name }) as any,
        ...(author && { author }) as any,
        ...(category && { category }) as any
    });
    return res.status(200).json({ success: true, data, total });
})

router.post('/', (req: Request, res: Response) => {
    // return res.json({ success: true });
    const body = req.body;
    const bookModel = new Book({ ...body });
    bookModel.save();
    return res.json({ success: true });
})

router.delete('/:id', async (req: Request, res: Response) => {
    const { id } = req.params;
    await Book.findByIdAndDelete(id);
    return res.status(200).json({ success: true });
})

router.put('/:id', async (req: Request, res: Response) => {
    const { id } = req.params;
    const body = req.body;
    await Book.findByIdAndUpdate({ _id: id }, body);
    return res.status(200).json({ success: true });
})

router.get('/:id', async (req: Request, res: Response) => {
    const { id } = req.params;
    const book = await Book.findById(id).populate('category');
    if (book) {
        return res.status(200).json({ success: true, data: book });
    } else {
        return res.status(500).json({ success: false })
    }
});

export default router;